package com.mypro.bookcity.dao;

import com.mypro.bookcity.dbUtil.DbUtil;
import com.mypro.bookcity.entity.User;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

public class UserDao {

    public User Login(String username, String password) {

        try {
            Connection cn = DbUtil.getConn();
            //根据用户名（唯一） 以及密码查询 最多只能查出一个
            PreparedStatement ps = cn.prepareStatement("select * from users where username=? and pw = ?");
            ps.setString(1, username);
            ps.setString(2, password);
            ResultSet rs = ps.executeQuery();
            if (rs.next()) {//能查询到就是登录成功
                User user = new User();
                user.setId(rs.getInt("id"));
                user.setUsername(rs.getString("username"));
                user.setPassword(rs.getString("pw"));
                user.setEmail(rs.getString("email"));
                return user;
            }
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {

            DbUtil.closeConn();
        }

        //查不到数据 返回null 表示登录失败
        return null;
    }


    public boolean addUser(String username,String password,String email){
        try {
            Connection cn=DbUtil.getConn();
            String add="insert into users(username,pw,email) values(?,?,?)";
            PreparedStatement ps=cn.prepareStatement(add);

            ps.setString(1,username);
            ps.setString(2,password);
            ps.setString(3,email);

            int result = ps.executeUpdate();
            return true;
        } catch (SQLException e) {
            // TODO 自动生成的 catch 块
            e.printStackTrace();
        }finally {
            DbUtil.closeConn();
        }
        return false;
    }

    public boolean checkusername(String username){
        try{
            Connection cn = DbUtil.getConn();
            String sql = "select count(*) as num from users where username = ?";
            PreparedStatement ps = cn.prepareStatement(sql);
            ps.setString(1,username);
            ResultSet rs = ps.executeQuery();
            if(rs.next()){
                Integer count = rs.getInt("num");
                if(count==0){//通过username查询出结果为0行记录才能表示这个username是可以去注册的
                    return true;
                }
            }
        }catch(SQLException e){
            e.printStackTrace();
        }finally {
            DbUtil.closeConn();
        }

        return false;
    }


}
